<?php
namespace App\Service\Admin;

use App\Service\BaseService as Service;
use Illuminate\Support\Facades\DB;

class OrderService extends Service
{
    public function updateRemark($id, $remark)
    {
        $res = (array) DB::table($this->dbOrder)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '该订单不存在');
        }
        $up = DB::table($this->dbOrder)
            ->where('id', $id)
            ->update(['remark' => $remark]);
        if (!$up) {
            return array('code' => -1, 'msg' => 'error');
        }
        return array('code' => 0, 'msg' => 'success');
    }

    /**
     * 订单列表
     * @param array $pas【status：1未付款，2审核中，3未发货；keyword：搜索词】
     * @param array $pages【start，limit】
     */
    public function getIndex($pas, $pages)
    {
        (new \App\Service\ApiXcx\OrderService())->autoAccept(); //自动收货
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = DB::table($this->dbOrder)->where('del', 0);
        $status = $pas['status'];
        $kword = $pas['keyword'];
        $phone = $pas['phone'];
        $ws = [];
        if ($status == 1) {
            $ws[] = ['iscancel', '=', 1];
            $ws[] = ['status', '=', 1];
            $db = $db->where($ws);
        } else if ($status == 2) {
            $ws[] = ['iscancel', '=', 2];
            $db = $db->where($ws);
        } else if ($status == 3) {
            $ws[] = ['iscancel', '=', 1];

            $ws[] = ['status', '=', 2];
            $db = $db->where($ws);
        }
        else if ($status == 4) {
            $ws[] = ['status', '=', 3];
            $db = $db->where($ws);
        }
        else if ($status == 5) {
            $ws[] = ['status', '=', 4];
            $db = $db->where($ws);
        }
        else {
        }
        if($pas['delivery']){


            $db = $db->where('delivery', $pas['delivery']);
        }
        if($pas['pay_way']){


            $db = $db->where('pay_way', $pas['pay_way']);
        }
        if ($kword) {
            //$ws[] = ['orderno', 'like', '%'.$kword.'%'];
            $db = $db->where('orderno', 'like', '%'.$kword.'%');
        }
        if ($phone) {
            $uOnes = $this->dbConn($this->dbUser)->where('phone', 'like', '%'.$phone.'%')->get();
            if (count($uOnes)) {
                $uids = [];
                foreach ($uOnes as $v) {
                    $v = (array) $v;
                    $uids[] = $v['id'];
                }
                $db = $db->whereIn('uid', $uids);
            }
        }
        if ($pas['start_day']) {
            $startDay = $pas['start_day'].' 00:00:01';
            $db = $db->where('addtime', '>=', $startDay);
        }
        if ($pas['end_day']) {
            $endDay = $pas['end_day'].' 23:59:59';
            $db = $db->where('addtime', '<=', $endDay);
        }
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            return array('code' => -2, 'msg' => '没有订单');
        }
        $status1s = $this->orderStatus1s;
        $status2s = $this->orderStatus2s;
        $cancels = $this->orderCancels;
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            //SKU信息
            $skuOnes = DB::table($this->dbOsku)->where('order_id', $v['id'])->get();
            $sku_name = '-';
            $priceTotal = $v['price'];
            $gname = '-';
            $gimg = '';
            $num = 0;
            if (count($skuOnes)) {
                $skuOne = (array) $skuOnes[0];
                $sku_name = $skuOne['sku_name'];
                $gname = $skuOne['gname'];
                foreach ($skuOnes as $skuOne) {
                    $skuOne = (array) $skuOne;
                    $num += $skuOne['num'];
                }
            }
            $v['price'] = $priceTotal / 100;
            $v['real_pay'] = $v['real_pay'] / 100;
            $v['cancel_name'] = array_key_exists($v['iscancel'], $cancels) ? $cancels[$v['iscancel']] : '-';
            if ($v['iscancel'] > 1) {
                $v['status_name'] = array_key_exists($v['iscancel'], $cancels) ? $cancels[$v['iscancel']] : '';
            } else if ($v['delivery'] == 1) {
                $v['status_name'] = array_key_exists($v['status'], $status1s) ? $status1s[$v['status']] : '';
            } else {
                $v['status_name'] = array_key_exists($v['status'], $status2s) ? $status2s[$v['status']] : '';
            }
            $v['sku_name'] = $sku_name;
            $v['gname'] = $gname;
            $v['gimg'] = $gimg;
            $v['num'] = $num;
            //收件人信息
            $v['accepter'] = ''; $v['acceptDoor'] = '';
            $addressOne = (array) $this->dbConn($this->dbUaddress)->where('id', $v['address_id'])->first();
            $v['accepter'] = empty($addressOne) ? '' : $addressOne['accepter'].'-'.$addressOne['phone'];
            $v['acceptDoor'] = empty($addressOne) ? '' : $addressOne['wx_name'].'-'.$addressOne['door'];
            $uOne = (array) $this->dbConn($this->dbUser)->where('id', $v['uid'])->first();
            $v['phone'] = empty($uOne) ? '-' : $uOne['phone'];
            //会员等级
            $uOne = (array) $this->dbConn($this->dbUser)
                ->where('id', $v['uid'])
                ->first();
            $v['level_name'] = '普通会员';
            if (!empty($uOne)&&$uOne['is_auto']) {
                if ($uOne['is_auto'] == 3) {
                    $v['level_name'] = 'SVIP会员';
                } else if (in_array($uOne['is_auto'], [1, 2])) {
                    $levelOne = (array) $this->dbConn($this->dbUlevel)
                        ->where('del', 0)
                        ->where('id', $uOne['level_id'])
                        ->first();
                    if (!empty($levelOne)) {
                        $v['level_name'] = $levelOne['title'];
                    }
                }
            }
            $arys[] = $v;
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => $total);
    }

    /**
     * 订单列表
     * @param array $pas【status：1未付款，2审核中，3未发货；keyword：搜索词】
     */
    public function getOlist($pas)
    {
        $db = DB::table($this->dbOrder)->where('del', 0);
        $status = $pas['status'];
        $kword = $pas['keyword'];
        $phone = $pas['phone'];
        $ws = [];
        if ($status == 1) {
            $ws[] = ['iscancel', '=', 1];
            $ws[] = ['status', '=', 1];
            $db = $db->where($ws);
        } else if ($status == 2) {
            $ws[] = ['iscancel', '=', 2];
            $db = $db->where($ws);
        } else if ($status == 3) {
            $ws[] = ['iscancel', '=', 1];
            $ws[] = ['delivery', '=', 1];
            $ws[] = ['status', '=', 2];
            $db = $db->where($ws);
        } else {
        }
        if ($kword) {
            $db = $db->where('orderno', 'like', '%'.$kword.'%');
        }
        if ($phone) {
            $uOnes = $this->dbConn($this->dbUser)->where('phone', 'like', '%'.$phone.'%')->get();
            if (count($uOnes)) {
                $uids = [];
                foreach ($uOnes as $v) {
                    $v = (array) $v;
                    $uids[] = $v['id'];
                }
                $db = $db->whereIn('uid', $uids);
            }
        }
        $total = $db->count();
        $res = $db->get();
        if (!count($res)) {
            return array('code' => -2, 'msg' => '没有订单');
        }
        $status1s = $this->orderStatus1s;
        $status2s = $this->orderStatus2s;
        $cancels = $this->orderCancels;
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            //SKU信息
            $skuOnes = DB::table($this->dbOsku)->where('order_id', $v['id'])->get();
            $sku_name = '-';
            $priceTotal = $v['price'];
            $gname = '-';
            $gimg = '';
            $num = 0;
            if (count($skuOnes)) {
                $skuOne = (array) $skuOnes[0];
                $sku_name = $skuOne['sku_name'];
                $gname = $skuOne['gname'];
                foreach ($skuOnes as $skuOne) {
                    $skuOne = (array) $skuOne;
                    $num += $skuOne['num'];
                }
            }
            $v['price'] = $priceTotal / 100;
            $v['real_pay'] = $v['real_pay'] / 100;
            $v['cancel_name'] = array_key_exists($v['iscancel'], $cancels) ? $cancels[$v['iscancel']] : '-';
            if ($v['iscancel'] > 1) {
                $v['status_name'] = array_key_exists($v['iscancel'], $cancels) ? $cancels[$v['iscancel']] : '';
            } else if ($v['delivery'] == 1) {
                $v['status_name'] = array_key_exists($v['status'], $status1s) ? $status1s[$v['status']] : '';
            } else {
                $v['status_name'] = array_key_exists($v['status'], $status2s) ? $status2s[$v['status']] : '';
            }
            $v['sku_name'] = $sku_name;
            $v['gname'] = $gname;
            $v['gimg'] = $gimg;
            $v['num'] = $num;
            //收件人信息
            $v['accepter'] = ''; $v['acceptDoor'] = '';
            $addressOne = (array) $this->dbConn($this->dbUaddress)->where('id', $v['address_id'])->first();
            $v['accepter'] = empty($addressOne) ? '' : $addressOne['accepter'].'-'.$addressOne['phone'];
            $v['acceptDoor'] = empty($addressOne) ? '' : $addressOne['wx_name'].'-'.$addressOne['door'];
            $uOne = (array) $this->dbConn($this->dbUser)->where('id', $v['uid'])->first();
            $v['phone'] = empty($uOne) ? '-' : $uOne['phone'];
            $arys[] = $v;
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => $total);
    }

    /**
     * 订单详情
     * @param int $id
     */
    public function getOne($id)
    {
        $res = (array) DB::table($this->dbOrder)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '订单不存在');
        }
        $status1s = $this->orderStatus1s;
        $status2s = $this->orderStatus2s;
        $cancels = $this->orderCancels;
        $deliverys = $this->orderDeliverys;
        //SKU信息
        $skuOnes = DB::table($this->dbOsku)->where('order_id', $res['id'])->get();
        $sku_name = '-';
        $gname = '-';
        $gimg = '';
        $num = 0;
        if (count($skuOnes)) {
            $skuOne = (array) $skuOnes[0];
            $sku_name = $skuOne['sku_name'];
            $gname = $gname!='-' ? $gname : $skuOne['gname'];
            foreach ($skuOnes as $skuOne) {
                $skuOne = (array) $skuOne;
                $num += $skuOne['num'];
            }
        }
        $res['price'] = $res['price'] / 100;
        $res['real_pay'] = $res['real_pay'] / 100;
        $res['cancel_name'] = array_key_exists($res['iscancel'], $cancels) ? $cancels[$res['iscancel']] : '-';
        if ($res['iscancel'] > 1) {
            $res['status_name'] = array_key_exists($res['iscancel'], $cancels) ? $cancels[$res['iscancel']] : '';
        } else if ($res['delivery'] == 1) {
            $res['status_name'] = array_key_exists($res['status'], $status1s) ? $status1s[$res['status']] : '';
        } else {
            $res['status_name'] = array_key_exists($res['status'], $status2s) ? $status2s[$res['status']] : '';
        }
        $res['sku_name'] = $sku_name;
        $res['gname'] = $gname;
        $res['gimg'] = $gimg;
        $res['num'] = $num;
        $res['deliveryName'] = array_key_exists($res['delivery'], $deliverys) ? $deliverys[$res['delivery']] : '';
        //收货地址
        $addressOne = (array) DB::table($this->dbUaddress)->where('id', $res['address_id'])->first();
        $res['accepter'] = empty($addressOne) ? '' : $addressOne['accepter'];
        $res['acceptName'] = empty($addressOne) ? '' : $addressOne['wx_door'];
        $res['acceptPhone'] = empty($addressOne) ? '' : $addressOne['phone'];
        //优惠劵
        $couponOne = (array) $this->dbConn($this->dbUcoupon)->where('id', $res['coupon_id'])->first();
        $res['quata'] = empty($couponOne) ? 0 : $couponOne['quata'];
        return array('code' => 0, 'msg' => 'success', 'data' => $res);
    }

    //订单审核
    public function setAuth($id, $status)
    {
        $res = (array) DB::table($this->dbOrder)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '该订单不存在');
        }
        if ($res['iscancel'] == 3) {
            return array('code' => -2, 'msg' => '该订单已通过审核');
        }
        $cancel = $status==1 ? 1 : 3;
        $up = DB::table($this->dbOrder)
            ->where('id', $id)
            ->update(['iscancel' => $cancel, 'cancelauthtime' => toDate()]);
        if (!$up) {
            return array('code' => -1, 'msg' => 'error');
        }
        //看看有没有优惠劵，待付款的可退还
        if ($res['status'] >= 2 && $res['coupon_id']) {
            $this->dbModify($this->dbOrder, ['id'=>$id], ['coupon_id'=>0]);
            $this->dbModify($this->dbUcoupon, ['id'=>$res['coupon_id']], ['status'=>2]);
        }
        $resData = [
            'uid' => $res['uid'],
            'orderno' => $res['orderno'],
        ];
        return array('code' => 0, 'msg' => 'success', 'data' => $resData);
    }

    //退货审核
    public function tuiAuth($id)
    {
        $res = (array) $this->dbConn($this->dbOrder)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return $this->toback(-2, '该订单不存在');
        }
        if ($res['tuihuo'] != 2) {
            return $this->toback(-2, '状态错误');
        }
        $up = DB::table($this->dbOrder)
            ->where('id', $id)
            ->update(['tuihuo' => 3, 'tuiauthtime' => toDate()]);
        if (!$up) {
            return $this->toback(-1, 'error');
        }
        //看看有没有优惠劵，待付款的可退还
        if ($res['status'] >= 2 && $res['coupon_id']) {
            $this->dbModify($this->dbOrder, ['id'=>$id], ['coupon_id'=>0]);
            $this->dbModify($this->dbUcoupon, ['id'=>$res['coupon_id']], ['status'=>2]);
        }
        return $this->toback();
    }

    /**
     * 订单发货
     * @param array $ids
     * @param array $pas
     */
    public function send($id, $pas)
    {
        $res = (array) $this->dbConn($this->dbOrder)
            ->where('del', 0)
            ->where('id', $id)
            ->where('iscancel', 1)
            ->where('delivery', 1)
            //->where('status', 2)
            ->first();
        if (empty($res)) {
            return $this->toback(-2, '该订单不存在或状态错误');
        }
        $up = DB::table($this->dbOrder)
            ->where('id', $id)
            ->update([
                'wuliu' => $pas['wuliu'], 'wuliuhao' => $pas['wuliuhao'],
                'status' => 3, 'sendtime' => toDate(),
            ]);
        if (!$up) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }

    /**
     *批量发货
     * @param array $os
     */
    public function batchSend($os)
    {
        foreach ($os as $o) {
            $id = $o['id'];
            $orderno = $o['orderno'];
            $wuliu = $o['wuliu'];
            $wuliuhao = $o['wuliuhao'];
            $res = (array) $this->dbConn($this->dbOrder)
                ->where('del', 0)
                ->where('id', $id)
                ->first();
            if (empty($res)) {
                return $this->toback(-2, $orderno.'订单不存在');
            }
//            if ($res['iscancel'] != 1) {
//                return array('code' => -2, 'msg' => $orderno.'订单非正常状态');
//            }
            if ($res['delivery'] != 1) {
                return array('code' => -2, 'msg' => $orderno.'订单属于自提');
            }
//            if ($res['status'] != 2) {
//                return array('code' => -2, 'msg' => $orderno.'订单状态错误');
//            }
            $up = $this->dbConn($this->dbOrder)->where('id', $id)
                ->update([
                    'wuliu' => $wuliu, 'wuliuhao' => $wuliuhao,
                    'status' => 3, 'sendtime' => toDate(),
                ]);
            if (!$up) {
                return $this->toback(-1, $orderno.'错误');
            }
        }
        return $this->toback();
    }
}